package org.hikari.qqbot.xiuxian.task;

import cn.hutool.core.util.TypeUtil;
import cn.hutool.json.JSONUtil;
import lombok.Getter;
import lombok.Setter;
import org.hikari.qqbot.xiuxian.service.bo.UserSetting;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * created at 2024-12-20 11:29:57
 *
 * @author yinchao
 * @version 1.0
 **/
@Getter
@Setter
public abstract class TypedITask<C> implements ITask {

    protected Map<Long, C> userConfigMap = new ConcurrentHashMap<>();

    public C config(Long userId) {
        return userConfigMap.get(userId);
    }

    public C config(UserSetting setting) {
        return userConfigMap.computeIfAbsent(setting.getUserId(), uid -> parseConfig(setting));
    }

    @Override
    public void initSetting(UserSetting setting) {
        C config = parseConfig(setting);
        userConfigMap.put(setting.getUserId(), config);
    }

    protected C parseConfig(UserSetting setting) {
        Map<String, Object> configs = setting.getActiveTasks().get(getId());
        if (configs == null) {
            configs = new HashMap<>();
        }
        Type configType = TypeUtil.getTypeArgument(getClass(), 0);
        return JSONUtil.toBean(JSONUtil.toJsonStr(configs), configType, false);
    }

}
